<?php
/**
 * 
 * 充值
 * @author alang
 *
 */

class Api_recharge_mdl extends Base_Controller
{
	
	const APPLEURL = 'https://buy.itunes.apple.com/verifyReceipt';
	
	
	
	
	public function __construct()
	{
		parent::__construct();
	}
	
	
	public function outputdata($data)
	{
		//$receiptdata
		if(!empty($data['USERID']) && !empty($data['EMAIL']) && !empty($data['TOKEN']) && !empty($data['RECEIPDATA'])){
			
			$json = $this->verify($data['RECEIPDATA']);
			$jarr = array();
			if (!empty($json)) {
				$jarr = json_decode($json, true);
				
				if (!empty($jarr['receipt'])) {
					
					$user['uid'] = $data['USERID'];
					$user['original_purchase_date_pst'] = $jarr['receipt']['original_purchase_date_pst'];
					$user['unique_identifier'] = $jarr['receipt']['unique_identifier'];
					$user['original_transaction_id'] = $jarr['receipt']['original_transaction_id'];
					$user['bvrs'] = $jarr['receipt']['bvrs'];
					$user['transaction_id'] = $jarr['receipt']['transaction_id'];
					$user['quantity'] = $jarr['receipt']['quantity'];
					$user['product_id'] = $jarr['receipt']['product_id'];
					$user['item_id'] = $jarr['receipt']['item_id'];
					$user['purchase_date_ms'] = $jarr['receipt']['purchase_date_ms'];
					$user['purchase_date'] = $jarr['receipt']['purchase_date'];
					$user['original_purchase_date'] = $jarr['receipt']['original_purchase_date'];
					$user['purchase_date_pst'] = $jarr['receipt']['purchase_date_pst'];
					$user['bid'] = $jarr['receipt']['bid'];
					$user['original_purchase_date_ms'] = $jarr['receipt']['original_purchase_date_ms'];
					$user['createtime'] = time();
								
					$user_now = $this->_getUserinfo($data['USERID']);
					$user['gold'] = $data['GOLD']+$user_now['txgoldnum'];

					if ($this->_recharge($user)) {
											
						$outputdata['TAG'] = $data['TAG'];
						$outputdata['STATUS'] = 0;
						$outputdata['ERRORMESSAGE'] = null;	
			
					} else {
											
						$outputdata['TAG'] = $data['TAG'];
						$outputdata['STATUS'] = 1;
						$outputdata['ERRORMESSAGE'] = 'SYSTEM ERROR';	
					
					}
					
				} else {
									
					$outputdata['TAG'] = $data['TAG'];
					$outputdata['STATUS'] = 1;
					$outputdata['ERRORMESSAGE'] = 'FAIL';	
			
				}
			} else {
				$outputdata['TAG'] = $data['TAG'];
				$outputdata['STATUS'] = 1;
				$outputdata['ERRORMESSAGE'] = 'SERVER BUESSING';
			}
			
		} else {
			
			$outputdata['TAG'] = $data['TAG'];
			$outputdata['STATUS'] = 1;
			$outputdata['ERRORMESSAGE'] = 'INFO ERROR';
		}
		
		header('Content-Type:text/html; charset=utf-8', false);
		echo json_encode($outputdata);
	}
	
	/**
	 * 
	 * 添加记录
	 * @param Array $data
	 */
	private function _recharge($data)
	{
		$this->db->insert('cj_recharge', $data);
		return ($this->db->affected_rows() > 0) ? $this->db->insert_id() : FALSE;
	}
	
	/**
	 * 
	 * POST模拟
	 * @param String $url
	 * @param Array $params
	 */
	private function fetch_page($url,$params=false) 
	{ 
	    $ch = curl_init(); 
	 
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
	    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
	    curl_setopt($ch,   CURLOPT_SSL_VERIFYPEER,   FALSE); 
	    curl_setopt($ch, CURLOPT_HTTPGET, true); 
	    curl_setopt($ch, CURLOPT_TIMEOUT, 4); 
	    if($params) 
	        curl_setopt($ch, CURLOPT_POSTFIELDS, $params); 
			curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'); 
			curl_setopt($ch, CURLOPT_URL,$url); 
	
	    $result = curl_exec($ch); 
	    return $result; 
	}
	
	/**
	 * 
	 * appstore验证
	 * @param unknown_type $receipt
	 */
	private function verify($receipt)
	{
	    $receipt      = trim($receipt);
	    $receipt_data = $receipt;
	
	    if (preg_match("/^<.+>$/", $receipt))
	    {
	        $receipt = preg_replace("/[^0-9a-fA-F]/","", $receipt);
	
	        // 如果是编码的票据，需要转码回来
	        $receipt_data = "";
	        for($i = 0; $i < strlen($receipt); $i = $i + 2)
	        {
	            $receipt_data = $receipt_data.chr(hexdec(substr($receipt, $i, 2)));
	        }
	    }
	
	    if (!preg_match("/^{.+}$/s", $receipt_data))
	    {
	        $receipt_data = base64_decode($receipt_data);
	    }
	
	    if (strpos($receipt_data, '"purchase-info"')===false)
	    {
	        return '{"receipt":{}, "status":"1"}';
	    }
	
	    $verify_url = 'https://sandbox.itunes.apple.com/verifyReceipt';
	    $verify_postfields = json_encode(array('receipt-data' => base64_encode($receipt_data)));
	    return $this->fetch_page($verify_url, $verify_postfields);
	}
	
	private function _getUserinfo($uid)
	{
		$user = array();
		$user = $this->db->select('user.uid,user.txemail,user.txusername,user.txgoldnum')
			->from('cj_users as user')
			->where('uid',$uid)
			->get()
			->row_array();
		
			return $user;
	}
	
}